package cn.wowjoy.office.materialmanage.add;


import android.arch.lifecycle.Observer;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;

import java.util.Map;

import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseFragment;
import cn.wowjoy.office.common.decoration.SimpleItemDecoration;
import cn.wowjoy.office.common.widget.CommonDialog;
import cn.wowjoy.office.common.widget.CreateDialog;
import cn.wowjoy.office.common.widget.MDialog;
import cn.wowjoy.office.data.response.RecordResponse;
import cn.wowjoy.office.data.response.StockRecordResponse;
import cn.wowjoy.office.databinding.FragmentAllBinding;
import cn.wowjoy.office.utils.ToastUtil;

/**
 * A simple {@link Fragment} subclass.
 */
public class AllFragment extends NewBaseFragment<FragmentAllBinding, AddReportViewModel> {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final int REQUEST_CODE1 = 1001;
    private static final int REQUEST_CODE2 = 1002;
    private static final int REQUEST_CODE3 = 1003;
    private int reqestcode;

    private MDialog waitDialog ;
    // TODO: Rename and change types of parameters
    private String status;
    private String headCode;
    private String key;
    private String barCode;
    private CommonDialog commonDialog;
    private String pageName;
    private int broadCount = 0;
    private boolean isResultBack;


    @Override
    protected Class<AddReportViewModel> getViewModel() {
        return AddReportViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_all;
    }


    private void initCommonDialog(){
        if (null == commonDialog)
            commonDialog = new CommonDialog.Builder()
                    .setTitle("提示")
                    .setContentGravity(Gravity.CENTER)
                    .setContent("该物资已有人录入，是否新增一条记录")
                    .setCancelBtn("否", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            commonDialog.dismiss();
                        }
                    })
                    .setConfirmBtn("是", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            goToReportDetail(barCode,headCode,null,false);
                            commonDialog.dismiss();
                        }
                    })
                    .create();
        commonDialog.show(getFragmentManager(),null);
    }



    public void setHeadCode(String headCode) {
        this.headCode = headCode;
        viewModel.setHeadCode(headCode);
        viewModel.getCountReportInfoByCodePDA(true);
    }

    public void setKey(String key) {
        this.key = key;
        viewModel.setKeyWord(key);
        viewModel.getCountReportInfoByCodePDA(true);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            headCode = getArguments().getString(ARG_PARAM1);
            status = getArguments().getString(ARG_PARAM2);
        }
        viewModel.setStatus(status);
        viewModel.setHeadCode(headCode);
        if (null == status){
            pageName = "全部";
            reqestcode = REQUEST_CODE1;
        } else if (TextUtils.equals("y",status)){
            pageName = "已录入";
            reqestcode = REQUEST_CODE2;
        } else if (TextUtils.equals("n",status)){
            pageName = "未录入";
            reqestcode = REQUEST_CODE3;
        }
    }

    @Override
    protected void onCreateViewLazy(Bundle savedInstanceState) {
        Log.d("tagAllFragement",pageName+"onCreateViewLazy");
       binding.setViewModel(viewModel);
       initRV();
       initObserve();

    }

    private void initRV(){
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.recyclerView.setAdapter(viewModel.lAdapter);
        binding.recyclerView.addItemDecoration(new SimpleItemDecoration(getContext(),SimpleItemDecoration.VERTICAL_LIST));
        binding.emptyView.emptyContent.setText("没有相关盘点报告");
        binding.recyclerView.setEmptyView(binding.emptyView.getRoot());
    }
    private void clearDialog(){
        if (waitDialog != null ){
            waitDialog.dismiss();
            waitDialog = null;
        }
    }


    private void goToReportDetail(String barCode,String reportHeadCode,String goodsCode, boolean isNotInReport){
        ARouter.getInstance().build("/materialmanage/addReport/stockRecord")
                .withString("barCode",barCode)
                .withString("headCode",reportHeadCode)
                .withString("goodsCode",goodsCode)
                .withBoolean("isNotInReport",isNotInReport)
                .navigation(getActivity(), REQUEST_CODE1);
    }

    @Override
    protected void brodcast(Context context, String msg) {
        super.brodcast(context, msg);
        barCode = msg;
        if (broadCount < 1){
            viewModel.isGoodsChecked(null,msg);
            ++broadCount;
        }

    }

    private void initObserve(){
        viewModel.recordList.observe(this, new Observer<LiveDataWrapper<StockRecordResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<StockRecordResponse> stockRecordResponseLiveDataWrapper) {
                switch (stockRecordResponseLiveDataWrapper.status){
                    case LOADING:
                        clearDialog();
                        waitDialog = CreateDialog.waitingDialog(getActivity());
                        break;
                    case SUCCESS:
                       clearDialog();
                        break;
                    case ERROR:
                        clearDialog();
                        handleException(stockRecordResponseLiveDataWrapper.error,true);
                        break;
                }
            }
        });
        viewModel.jumpTo.observe(this, new Observer<RecordResponse>() {
            @Override
            public void onChanged(@Nullable RecordResponse recordResponse) {
                goToReportDetail(null,recordResponse.getHeadCode(),recordResponse.getGoodsCode(),false);
            }
        });
        viewModel.isGoodsChecked.observe(this, new Observer<LiveDataWrapper<Map<String,String>>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<Map<String,String>> stringLiveDataWrapper) {
                broadCount = 0;
                switch (stringLiveDataWrapper.status){
                    case LOADING:
                        clearDialog();
                        waitDialog = CreateDialog.waitingDialog(getActivity());
                        break;
                    case SUCCESS:
                       clearDialog();
                        if (TextUtils.equals("y",stringLiveDataWrapper.data.get("isHasGoods"))){
                            if (TextUtils.equals("y",stringLiveDataWrapper.data.get("isInReport"))){
                                if (TextUtils.equals("y",stringLiveDataWrapper.data.get("isChecked"))){
                                    initCommonDialog();
                                } else {
                                    goToReportDetail(barCode,headCode,null,false);
                                }
                            } else {
                                //跳转至库存录入页面，调主数据详情接口
                                goToReportDetail(barCode,headCode,null,true);

                            }
                        } else {
                            Toast.makeText(getActivity(), "主数据中暂未录入该物资。", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case ERROR:
                        clearDialog();
                        handleException(stringLiveDataWrapper.error, false);
                        break;
                }
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        isResultBack = true;
        switch (requestCode){
            case REQUEST_CODE1:
                if (null != data && data.getBooleanExtra("isSave",false)){
                    viewModel.getCountReportInfoByCodePDA(true);
                }
                break;
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Log.d("tagAllFragement",pageName+"onHiddenChanged");
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.d("tagAllFragement",pageName+"setUserVisibleHint");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d("tagAllFragement",pageName+"onResume");
    }

    @Override
    protected void onResumeLazy() {
        super.onResumeLazy();
        Log.d("tagAllFragement",pageName+"onResumeLazy");
            openBroadCast();
        if (!TextUtils.isEmpty(headCode) && !isResultBack){
             viewModel.getCountReportInfoByCodePDA(true);
        }
        if (isResultBack){
            isResultBack = false;
        }

    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d("tagAllFragement",pageName+"onStop");
    }

    @Override
    protected void onStopLazy() {
        super.onStopLazy();
        closeBroadCast();
        Log.d("tagAllFragement",pageName+"onStopLazy");

    }

    @Override
    protected ViewGroup getErrorViewRoot() {
        return binding.flError;
    }

    @Override
    protected void refreshError() {
        super.refreshError();
        viewModel.getCountReportInfoByCodePDA(true);
    }


    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HomeFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static AllFragment newInstance(String param1, String param2) {
        AllFragment allFragment = new AllFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        allFragment.setArguments(args);
        return allFragment;
    }

}
